package com.lishuang.DAO.visitLogDAO;

import com.lishuang.DAO.SqlConnector;
import com.lishuang.domain.json.Device;
import com.lishuang.services.DAOService;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author LiShuang
 * @version 1.0.0
 * @date 2022/11/16 18:13
 */
public class vLogDAOImp implements vLogDAO{

    private SqlConnector sql;
    private PreparedStatement statement;
    public vLogDAOImp(SqlConnector sql){this.sql=sql;}
    @Override
    public boolean Insert(Device device) throws Exception {
        String query = "INSERT INTO `visitlog` (`deviceID`,`priority`, `submittime`,`executetime`) VALUES (?,?,?,?)";

        statement=sql.getConnection().prepareStatement(query);
        statement.setInt(1,device.getDeviceId());
        statement.setInt(2, device.getDevicePriority());
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        Timestamp now = new Timestamp(new Date().getTime());
        statement.setTimestamp(3,DAOService.submittime);
        statement.setTimestamp(4,now);
        int update = statement.executeUpdate();
        if(update>0){
            return true;
        }
        else{
            return false;
        }
    }



    @Override
    public List<visitLog> findAll() throws Exception {
        List<visitLog> list = new ArrayList<>();
        visitLog v;
        String sqlString = "SELECT deviceID,priority,submittime, executetime FROM visitlog";
        statement = sql.getConnection().prepareStatement(sqlString);
        ResultSet rSet = statement.executeQuery();

        //getMetaData获得表结构，getColunmCount获得字段数
        while (rSet.next()) {
            v = new visitLog();
            v.deviceId= rSet.getInt("deviceId");
            v.priority=rSet.getInt("priority");
            v.submittime= rSet.getTimestamp("submittime");
            v.executetime= rSet.getTimestamp("executetime");
            list.add(v);
            System.out.println(v);
        }
        System.out.println(list);
        return list;
    }

    @Override
    public Device findByIdx(int deviceId) throws Exception {
        return null;
    }

    @Override
    public boolean deleteAll() throws Exception {
        String sqlString = "truncate TABLE visitlog";
        statement = sql.getConnection().prepareStatement(sqlString);
        return statement.execute();
    }
}

